<?php

namespace app\ruinuo\service\make;

use app\common\model\RuinuoMake;
use app\common\model\AdminMenu;
use app\common\model\RuinuoApp;
use app\common\model\RuinuoMode;
use app\common\model\AdminOptions;
use think\facade\Config;
use think\facade\Db;
use app\common\model\RuinuoSetting;

class Make
{

    public function Index($id = 0)
    {
        $RuinuoMake = new RuinuoMake();
        $RuinuoMode = new RuinuoMode();
        $RuinuoApp = new RuinuoApp();
        $Make = $RuinuoMake->where("id='" . $id . "'")->find();
        $modes = $RuinuoMode->where("id in(" . $Make['mode_ids'] . ")")->select()->toArray();
        $Make['app_ids'] = '';
        foreach ($modes as $k => $v) {
            $app = $RuinuoApp->where("id='" . $v['app_id'] . "'")->field("num")->findOrEmpty()->toArray();
            $modes[$k]['app_num'] = $app['num'];
            $Make['app_ids'] .= $v['app_id'] . ',';
        }
        $Make['mode'] = $modes;
        $Make['app_ids'] = rtrim($Make['app_ids'], ",");
        if ($Make['options_ids']) {
            $options_ids = explode(',', $Make['options_ids']);
            $ids = "";
            $AdminOptions = new AdminOptions();
            foreach ($options_ids as $k => $v) {
                $Options = $AdminOptions->where("num='" . $v . "' and is_delete=0")->field("id")->findOrEmpty()->toArray();
                if ($Options) {
                    $ids .= $Options['id'] . ',';
                }
            }
            $Make['options_ids'] = rtrim($ids, ",");
        }
        $this->deldir(App()->getRootPath() . 'make_addon/' . $Make['num'] . '/');
        $file = [
            App()->getRootPath() . 'make_addon/',
            App()->getRootPath() . 'make_addon/' . $Make['num'] . '/',
            App()->getRootPath() . 'make_addon/' . $Make['num'] . '/database/',
            App()->getRootPath() . 'make_addon/' . $Make['num'] . '/path/',
            App()->getRootPath() . 'make_addon/' . $Make['num'] . '/config/',
        ];
        foreach ($file as $k => $v) {
            $this->MkdirFile($v);
        }
        if (!empty($Make['menu_ids'])) {
            $AdminMenu = new AdminMenu();
            $where = "(id in(" . $Make['menu_ids'] . ") or (parent_id in(" . $Make['menu_ids'] . ") and type!=1)) and is_delete=0";
            $Menu = $AdminMenu->where($where)->field("id,parent_id,type")->select()->toArray();
            $ids = '';
            foreach ($Menu as $k => $v) {
                $ids .= $v['id'] . ',';
            }
            $Make['menu_ids'] = rtrim($ids, ",");
        }
        $Make['setting'] = [];
        if (!empty($Make['seting_ids'])) {
            $RuinuoSetting = new RuinuoSetting();
            $setting = $RuinuoSetting->where("id in(" . $Make['seting_ids'] . ")")->field("num")->select()->toArray();
            foreach ($setting as $k => $v) {
                $setting[$k]['app_num'] = 'setting';
                $setting[$k]['database'] = 'ruinuo_setting';
            }
            $Make['setting'] = $setting;
        }
        $this->DataBase($Make);
        $this->Files($Make);
    }



    public function DataBase($Make = [])
    {
        $mode = $Make['mode'];
        $installPath = App()->getRootPath() . "make_addon" . DS . $Make['num'] . DS . "database" . DS . "install.sql";
        $uninstallPath = App()->getRootPath() . "make_addon" . DS . $Make['num'] . DS . "database" . DS . "uninstall.sql";
        file_put_contents($installPath, "SET NAMES utf8mb4;\r\nSET FOREIGN_KEY_CHECKS = 0;\r\n");
        file_put_contents($uninstallPath, "SET NAMES utf8mb4;\r\n");
        foreach ($mode as $k => $v) {
            $this->downSql(1, $v['database'], $installPath);
            file_put_contents($uninstallPath, "DROP TABLE IF EXISTS `" . $v['database'] . "`;\r\n", FILE_APPEND);
        }
        if (!empty($Make['app_ids'])) {
            $this->downSql(3, 'ruinuo_app', $installPath, 'id', 'in', '(' . $Make['app_ids'] . ')');
        }
        $this->downSql(3, 'ruinuo_mode', $installPath, 'id', 'in', '(' . $Make['mode_ids'] . ')');
        $this->downSql(3, 'ruinuo_form', $installPath, 'mode_id', 'in', '(' . $Make['mode_ids'] . ')');
        $this->downSql(3, 'ruinuo_table', $installPath, 'mode_id', 'in', '(' . $Make['mode_ids'] . ')');
        if (!empty($Make['menu_ids'])) {
            $this->downSql(3, 'admin_menu', $installPath, 'id', 'in', '(' . $Make['menu_ids'] . ')');
        }
        if (!empty($Make['options_ids'])) {
            $this->downSql(3, 'admin_options', $installPath, 'id', 'in', '(' . $Make['options_ids'] . ')');
            file_put_contents($uninstallPath, "DELETE FROM `admin_options` WHERE `id` in(" . $Make['options_ids'] . ");\r\n", FILE_APPEND);
        }
        if (!empty($Make['seting_ids'])) {
            $this->downSql(3, 'ruinuo_setting', $installPath, 'id', 'in', '(' . $Make['seting_ids'] . ')');
            file_put_contents($uninstallPath, "DELETE FROM `ruinuo_setting` WHERE `id` in(" . $Make['seting_ids'] . ");\r\n", FILE_APPEND);
        }
        file_put_contents($installPath, 'SET FOREIGN_KEY_CHECKS = 1;', FILE_APPEND);
        file_put_contents($uninstallPath, "DELETE FROM `ruinuo_mode` WHERE `id` in(" . $Make['mode_ids'] . ");\r\n", FILE_APPEND);
        file_put_contents($uninstallPath, "DELETE FROM `ruinuo_form` WHERE `mode_id` in(" . $Make['mode_ids'] . ");\r\n", FILE_APPEND);
        file_put_contents($uninstallPath, "DELETE FROM `ruinuo_table` WHERE `mode_id` in(" . $Make['mode_ids'] . ");\r\n", FILE_APPEND);
    }

    public function Files($Make = [])
    {
        $mode = $Make['mode'];
        if (!empty($Make['setting'])) {
            $mode = array_merge($mode, $Make['setting']);
        }
        $RootPath = App()->getRootPath() . 'make_addon/' . $Make['num'] . '/path/';
        foreach ($mode as $k => $v) {
            $this->MkdirFile($RootPath . 'app/' . $v['app_num'] . '/controller/');
            $service = 'app/' . $v['app_num'] . '/service/' . $v['num'] . '/';
            $this->MkdirFile($RootPath . $service);
            $template = 'app/common/template/' . $v['app_num'] . '/' . $v['num'] . '/';
            $this->MkdirFile($RootPath . $template);
            $this->MkdirFile($RootPath . 'app/common/model/');
            $static = 'public/static/js/' . $v['app_num'] . '/' . $v['num'] . '/';
            $this->MkdirFile($RootPath . $static);
            $ModePath = 'app/common/model/' . ucfirst(GetCamelize($v['database'])) . '.php';
            copy(App()->getRootPath() . $ModePath, $RootPath . $ModePath);
            $controllerPath = 'app/' . $v['app_num'] . '/controller/' . ucfirst($v['num']) . '.php';
            copy(App()->getRootPath() . $controllerPath, $RootPath . $controllerPath);
            $this->CopyPath(App()->getRootPath() . $service, $RootPath . $service, 1);//复制文件到对应目录
            $this->CopyPath(App()->getRootPath() . $template, $RootPath . $template, 1);//复制文件到对应目录
            $this->CopyPath(App()->getRootPath() . $static, $RootPath . $static, 1);//复制文件到对应目录
        }
    }


    public function CopyPath($source, $destination, $child, $fileb = '')
    {

        if (!file_exists($destination)) {
            if (!mkdir(rtrim($destination, '/'), 0777, true)) {
                return false;
            }
            @chmod($destination, 0777);
        }
        if (!is_dir($source)) {
            return false;
        }
        if (!is_dir($destination)) {
            mkdir($destination, 0777, true);
        }
        $handle = dir($source);
        while ($entry = $handle->read()) {
            if (($entry != ".") && ($entry != "..")) {
                if (is_dir($source . "/" . $entry)) {
                    if ($child)
                        $this->CopyPath($source . "/" . $entry, $destination . "/" . $entry, $child, $fileb);
                } else {
                    if ($fileb) {
                        if (strpos($fileb, $entry) !== false) {
                            copy($source . "/" . $entry, $destination . "/" . $entry);
                        }
                    } else {
                        copy($source . "/" . $entry, $destination . "/" . $entry);
                    }
                }
            }
        }
        return true;
    }

    public function MkdirFile($path)
    {
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
    }
    //删除目录及文件
    public function deldir($dir='')
    {
        if (is_dir($dir)) {
            $dh = opendir($dir);
            while ($file = readdir($dh)) {
                if ($file != "." && $file != "..") {
                    $fullpath = $dir . "/" . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        $this->deldir($fullpath);
                    }
                }
            }
            closedir($dh);
            if (rmdir($dir)) {
                return true;
            } else {
                return false;
            }
        }
    }


    public function downSql($type = 1, $table = '', $to_file_name = '', $field = '', $expre = '', $condition = '')
    {
        $prefix = Config::get('database.connections.mysql.prefix');
        $sqlTable = Config::get('database.connections.mysql.prefix') . $table;
        if ($type == 1 || $type == 2) {
            /**********② 导出数据表结构**************/
            $sql = "show create table " . $sqlTable;
            $res = Db::query($sql);
            $info = "-- ----------------------------\r\n";
            $info .= "-- Table structure for `" . $table . "`\r\n";
            $info .= "-- ----------------------------\r\n";
            $info .= "DROP TABLE IF EXISTS `" . $table . "`;\r\n";
            $CreateTable = $res[0]['Create Table'];
            $CreateTable = str_replace('`' . $prefix, '`', $CreateTable);
            $sqlStr = $info . $CreateTable . ";\r\n\r\n";
            file_put_contents($to_file_name, $sqlStr, FILE_APPEND);
            /**********导出数据**************/
        }

        if ($type == 1 || $type == 3) {
            // ③ 根据输入条件组装查询条件
            if (!empty($field) && !empty($expre) && !empty($condition)) {

                $where = "where" . " " . $field . " " . $expre . " " . $condition;
                // 查询语句
                $sql = "select * from " . $sqlTable . " " . $where;
            } else {
                // 查询语句
                $sql = "select * from " . $sqlTable;
            }
            $res = Db::query($sql);
            // 判断数据是否为空
            if (count($res) >= 1) {
                $info = "-- ----------------------------\r\n";
                $info .= "-- Records for `" . $table . "`\r\n";
                $info .= "-- ----------------------------\r\n";
                file_put_contents($to_file_name, $info, FILE_APPEND);
                /**********④ 拼接插入数据格式**************/
                foreach ($res as $v) {
                    $sqlStr = "INSERT IGNORE INTO `" . $table . "` VALUES (";
                    // 循环出字段对应的数据，并组装
                    foreach ($v as $zd) {
                        // 替换数据中的换行符
                        $zd = str_replace("\r\n", "", $zd);
                        if (strlen($zd) == 0) {
                            $sqlStr .= "NULL, ";
                        } else {
                            $sqlStr .= "'" . addslashes($zd) . "', ";
                        }
                    }
                    //去掉最后一个逗号和空格
                    $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 2);
                    $sqlStr .= ");\r\n";
                    // ⑤ 写入文件
                    file_put_contents($to_file_name, $sqlStr, FILE_APPEND);
                }
                file_put_contents($to_file_name, "\r\n", FILE_APPEND);
            }
        }

    }


}